<template>
    <NSpace vertical>
        <n-radio-group v-model:value="data_mode" name="data_mode">
            <n-radio-button v-for="mode in data_modes" :key="mode.value" :value="mode.value" :label="mode.label" />
        </n-radio-group>
        <n-radio-group v-model:value="show_mode" name="show_modes">
            <n-radio-button v-for="mode in show_modes" :key="mode.value" :value="mode.value" :label="mode.label" />
        </n-radio-group>
        <v-chart :key="refreshKey" :option="option" autoresize
            style="background-color: #66ccff33;width: 100%;height: 600px;touch-action: none;overscroll-behavior: none;user-select: none;" />
    </NSpace>

</template>

<script setup>
import { NRadioGroup, NRadioButton, NSpace } from 'naive-ui'
import { computed, onMounted, ref, watch } from 'vue'

import { use, registerMap } from "echarts/core";
import VChart from "vue-echarts";
import chinaMap from "@/api/getChinaMap";
import { MapChart, BarChart } from 'echarts/charts'
import { TitleComponent, VisualMapComponent, GeoComponent, TooltipComponent, GridComponent, DataZoomComponent } from 'echarts/components'
import { UniversalTransition } from 'echarts/features'
import { SVGRenderer, CanvasRenderer } from 'echarts/renderers'

import {
    getStudentSource,
    getExcellentStudentSource,
    getPoorStudentSource
} from "@/api/studentSource"

import convertProvince from "../tools/convertProvince";



use([
    TitleComponent, VisualMapComponent,
    GeoComponent,
    MapChart,
    CanvasRenderer,
    UniversalTransition, TooltipComponent, BarChart, GridComponent, DataZoomComponent,
])


const refreshKey = ref(0);

chinaMap.then((res) => {
    registerMap("china", res.data);
    refreshKey.value++;
    console.log(option);
}).catch((err) => {
    console.error("Error loading China map data:", err);
    registerMap("china", {
        type: "FeatureCollection",
        features: []
    });
    refreshKey.value++;
});

const option_map = computed(() => {
    return {
        title: {
            text: data_mode_label.value + "统计图 - " + show_mode_label.value,
            left: 'center',
            top: 0
        },
        tooltip: {
            trigger: 'item',          // 鼠标悬停/触摸时显示
            formatter: '{b}: {c}',    // {b} 名称，{c} 数值
            // position: ['50%', '10%'], // 可选：固定屏幕位置
            backgroundColor: 'rgba(0,0,0,0.7)',
            textStyle: { color: '#fff' }
        },
        visualMap: {
            left: 'right',
            min: 0,
            max: 5000,
            inRange: {
                // prettier-ignore
                color: ['#ffffff', 'green', 'green', 'green', 'green', 'green', 'green']
            },
            text: ['High', 'Low'],
            calculable: true
        },
        series: [
            {
                id: 'population',
                type: 'map',
                roam: true,
                scaleLimit: {
                    min: 1,
                    max: 3
                },
                map: 'china',
                animationDurationUpdate: 1000,
                universalTransition: true,
                data: student_data.value
            }
        ]
    }
})


const option_bar = computed(() => {
    console.log(student_data.value);

    return {
        title: {
            text: data_mode_label.value + "统计图 - " + show_mode_label.value,
            left: 'center',
            top: 0
        },
        tooltip: {
            trigger: 'item',          // 鼠标悬停/触摸时显示
            formatter: '{b}: {c}',    // {b} 名称，{c} 数值
            // position: ['50%', '10%'], // 可选：固定屏幕位置
            backgroundColor: 'rgba(0,0,0,0.7)',
            textStyle: { color: '#fff' }
        },
        grid: [
            { left: '120', top: '7%', width: '60%', height: '80%' },
        ],
        xAxis: {
            type: 'value'
        },
        yAxis: {
            type: 'category',
            axisLabel: {
                rotate: 0,
                hideOverlap: false,
            },
            data: student_data.value.map(function (item) {
                return item.name;
            })
        },
        dataZoom: [
            {
                type: 'slider',
                show: true,
                yAxisIndex: [0],
                right: '0%',
                start: 0,
                end: 100
            },
            {
                type: 'inside',
                yAxisIndex: [0],
                start: 29,
                end: 36
            }
        ],
        animationDurationUpdate: 1000,


        series: [{
            type: 'bar',
            id: 'population',
            data: student_data.value.map(function (item) {
                return item.value;
            }),
            universalTransition: true
        }
        ]
    };
})


const option = computed(() => {
    if (show_mode.value === 'map') {
        return option_map.value;
    } else if (show_mode.value === 'bar') {
        return option_bar.value;
    }
    return option_map.value;
})






const show_mode = ref('bar')

const show_mode_label = computed(() => {
    const mode = show_modes.value.find(m => m.value === show_mode.value)
    return mode ? mode.label : ''
})

const show_modes = ref([
    { label: '地图模式', value: 'map' },
    { label: '数据视图', value: 'bar' },
])



const data_mode = ref('all')

const data_mode_label = computed(() => {
    const mode = data_modes.value.find(m => m.value === data_mode.value)
    return mode ? mode.label : ''
})

const data_modes = ref([
    { label: '总生源', value: 'all' },
    { label: '优秀学子', value: 'nice' },
    { label: '贫困学子', value: 'poor' }
])


onMounted(() => {
    getStudentSource().then((res) => {
        console.log(res.data.data);

        student_data.value = res.data.data.map(({ id, count }) => ({
            name: convertProvince(id),
            value: count
        }));
    })


})


const student_data = ref([])


watch(
    data_mode,
    async (mode) => {
        const api = {
            all: getStudentSource,
            nice: getExcellentStudentSource,
            poor: getPoorStudentSource
        }[mode] || (() => Promise.resolve({ data: { data: [] } }))

        const res = await api()
        student_data.value = res.data.data.map(({ id, count }) => ({
            name: convertProvince(id),
            value: count
        }))
    },
    { immediate: true }   // 首次自动执行一次
)

// const student_data = computed(() => {
//     switch (data_mode.value) {
//         case 'all':
//             getStudentSource().then((res) => {
//                 console.log(res.data.data.map(({ id, count }) => ({
//                     name: convertProvince(id),
//                     value: count
//                 })));



//                 return res.data.data.map(({ id, count }) => ({
//                     name: convertProvince(id),
//                     value: count
//                 }));
//             })
//             break;
//         case 'nice':
//             getExcellentStudentSource().then((res) => {
//                 return res.data.data.map(({ id, count }) => ({
//                     name: convertProvince(id),
//                     value: count
//                 }));
//             })
//             break;
//         case 'poor':
//             getPoorStudentSource().then((res) => {
//                 return res.data.data.map(({ id, count }) => ({
//                     name: convertProvince(id),
//                     value: count
//                 }));
//             })
//             break;

//         default:
//             break;
//     }


//     return;
// })





const student_data_old = ref([
    { "name": "北京市", "value": 4 },
    { "name": "天津市", "value": 50 },
    { "name": "河北省", "value": 326 },
    { "name": "山西省", "value": 130 },
    { "name": "内蒙古自治区", "value": 30 },
    { "name": "辽宁省", "value": 30 },
    { "name": "吉林省", "value": 30 },
    { "name": "黑龙江省", "value": 40 },
    { "name": "江苏省", "value": 80 },
    { "name": "浙江省", "value": 101 },
    { "name": "安徽省", "value": 37 },
    { "name": "福建省", "value": 60 },
    { "name": "江西省", "value": 63 },
    { "name": "山东省", "value": 4880 },
    { "name": "河南省", "value": 223 },
    { "name": "湖北省", "value": 180 },
    { "name": "湖南省", "value": 93 },
    { "name": "广东省", "value": 116 },
    { "name": "广西壮族自治区", "value": 76 },
    { "name": "海南省", "value": 20 },
    { "name": "重庆市", "value": 40 },
    { "name": "四川省", "value": 95 },
    { "name": "贵州省", "value": 113 },
    { "name": "云南省", "value": 61 },
    { "name": "西藏自治区", "value": 20 },
    { "name": "陕西省", "value": 50 },
    { "name": "甘肃省", "value": 80 },
    { "name": "青海省", "value": 40 },
    { "name": "宁夏回族自治区", "value": 10 },
    { "name": "新疆维吾尔自治区", "value": 10 }
]);





</script>
